import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

class DialogTest extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _DialogTestState();
  }
}

class _DialogTestState extends State<DialogTest> {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: _buildButtons(),
    );
  }

  List<Widget> _buildButtons() {
    return [
      FlatButton(
        color: Color(0xFF88FFAA),
        child:
            Text("Simple dialog", style: TextStyle(color: Color(0xffffffff))),
        onPressed: () {
          _showSimpleDialog();
        },
      ),
      FlatButton(
        color: Color(0xFF889911),
        child:
            Text("Material dialog", style: TextStyle(color: Color(0xffffffff))),
        onPressed: () {
          _showMaterialDialog();
        },
      ),
      FlatButton(
        color: Color(0xFFFF99BB),
        child: Text(
          " Cupertino dialog",
          style: TextStyle(color: Color(0xffffffff)),
        ),
        onPressed: () {
          _showIosDialog();
        },
      ),
      FlatButton(
        color: Color(0xFF1199BB),
        child: Text(
          "ListViewDialog",
          style: TextStyle(color: Color(0xffffffff)),
        ),
        onPressed: () {
          _showListDialog();
        },
      ),
      FlatButton(
        color: Color(0xFF5555BB),
        child: Text(
          "Multiple choice dialog",
          style: TextStyle(color: Color(0xffffffff)),
        ),
        onPressed: () {
          _showMultipleSelectDialog();
        },
      ),
      FlatButton(
        color: Color(0xFFFF55BB),
        child: Text(
          "Single choice dialog",
          style: TextStyle(color: Color(0xffffffff)),
        ),
        onPressed: () {
          _showSingleSelectDialog();
        },
      ),
      FlatButton(
        color: Color(0xFFFF55BB),
        child: Text(
          "Custom Loading Dialog",
          style: TextStyle(color: Color(0xffffffff)),
        ),
        onPressed: () {
          showCustomLoadingDialog();
        },
      ),
      Container(
        color: Colors.red,
        child: Stack(
          children: <Widget>[
            Container(
              width: 50,
              height: 50,
              color: Colors.deepPurple,
            ),
            Container(
              color: Colors.amber,
              margin: EdgeInsets.only(right: 5),
              child: Text(
                '哈哈达12121212到',
                style: TextStyle(fontSize: 60.0),
              ),
            ),

            Positioned(
              top: 0,
              bottom: 0,
              right: 0,
              child: Container(
                color: Colors.lightBlue,
                width: 5,
              ),
            )
          ],
        ),
      )
    ];
  }

  ///显示一个一般的dialog
  void _showSimpleDialog() {
    //showDialog得到的是一个 Future<T> ,可以利用then获取到 用户选择的是"确定"或者"取消",需要在关闭dialog的时候，将数据传递回来如下面的
    //Navigator.of(context).pop("确定")
    showDialog(
        barrierDismissible: false, //这个属性控制在dialog之外点击，是否关闭dialog，为false不关闭
        context: context,
        builder: (context) => SimpleDialog(
              title: Text("SimpleDialog"),
              titlePadding: EdgeInsets.all(16),
              contentPadding: EdgeInsets.all(16),
              children: <Widget>[
                Container(
//                  height: 100,
                  child: Text("这是一个SimpleDialog"),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    FlatButton(
                      child: Text("取消"),
                      onPressed: () {
                        Navigator.of(context).pop("取消");
                      },
                    ),
                    FlatButton(
                      child: Text("确定"),
                      onPressed: () {
                        Navigator.of(context).pop("确定");
                      },
                    )
                  ],
                )
              ],
// 可以自定义shape
//              shape: RoundedRectangleBorder(
//                  side: BorderSide(color: Color(0xFFFFCCFF), width: 2.0),
//                  borderRadius: BorderRadius.circular(40.0)),
            )).then((value) => print(value));
  }

  ///显示Material风格的 dialog
  void _showMaterialDialog() {
    showDialog(
        barrierDismissible: true,
        context: context,
        builder: (context) => AlertDialog(
              title: Text("AlertDialog"),
              content: Text("this is a AlertDialog"),
              actions: <Widget>[
                FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop("取消");
                  },
                  child: Text("取消"),
                ),
                FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop("确定");
                  },
                  child: Text("确定"),
                )
              ],
            )).then((value) => print(value));
  }

  ///显示一个ios风格的 dialog
  void _showIosDialog() {
    showDialog(
        context: context,
        builder: (context) => CupertinoAlertDialog(
              title: Text("Cupertino"),
              actions: <Widget>[
                FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop("取消");
                  },
                  child: Text("取消"),
                ),
                FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop("确定");
                  },
                  child: Text("确定"),
                )
              ],
              content: Text(
                  "这是一个ios风格的dialog这是一个ios风格的dialog这是一个ios风格的dialog这是一个ios风格的dialog这是一个ios风格的dialog这是一个ios风格的dialog"),
            )).then((value) => print(value));
  }

  ///对于有一个 可滑动列表的 dialog需要用 container来定死宽高
  void _showListDialog() {
    showDialog(
        context: context,
        builder: (context) => AlertDialog(
              title: Text("Dialog has a list"),
              contentPadding:
                  EdgeInsets.symmetric(vertical: 12, horizontal: 24),
              content: Container(
                height: 120,
                width: 200,
                child: ListView.builder(
                  itemBuilder: (context, index) => InkWell(
                        child: Text("content $index"),
                        onTap: () {
                          Navigator.of(context).pop("on click $index");
                        },
                      ),
                  itemCount: 8,
                ),
              ),
              actions: <Widget>[
                FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop("取消");
                  },
                  child: Text("取消"),
                ),
                FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop("确定");
                  },
                  child: Text("确定"),
                )
              ],
            )).then((value) => print(value));
  }

  /// 多选    dialog
  void _showMultipleSelectDialog() {
    final List listData = [
      {'index': 0, 'isSelected': false},
      {'index': 1, 'isSelected': false},
      {'index': 2, 'isSelected': false},
      {'index': 3, 'isSelected': false},
      {'index': 4, 'isSelected': false},
      {'index': 5, 'isSelected': false},
      {'index': 6, 'isSelected': false},
      {'index': 7, 'isSelected': false},
    ];

    showDialog(
        context: context,
        builder: (context) => AlertDialog(
              title: Text("Multiple select Dialog"),
              contentPadding:
                  EdgeInsets.symmetric(vertical: 12, horizontal: 24),
              content: Container(
                height: 240,
                width: 200,
                child: ListView.builder(
                  itemBuilder: (context, index) => StatefulBuilder(
                        builder: (context, StateSetter setState) {
                          return Container(
                            child: CheckboxListTile(
                                title: Text("选择$index"),
                                value: listData[index]['isSelected'],
                                onChanged: (value) {
                                  setState(() =>
                                      listData[index]['isSelected'] = value);
                                }),
                          );
                        },
                      ),
                  itemCount: listData.length,
                ),
              ),
              actions: <Widget>[
                FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop("取消");
                  },
                  child: Text("取消"),
                ),
                FlatButton(
                  onPressed: () {
                    //采集被选中的项

                    String hasSeletItem = "";
                    listData.forEach((item) {
                      if (item['isSelected']) {
                        hasSeletItem = "$hasSeletItem ${item['index']} ";
                      }
                    });

                    Navigator.of(context).pop(hasSeletItem);
                  },
                  child: Text("确定"),
                )
              ],
            )).then((value) => print(value));
  }

  /// 单选    dialog
  void _showSingleSelectDialog() {
    final List listData = [
      {'index': 0, 'isSelected': false},
      {'index': 1, 'isSelected': false},
      {'index': 2, 'isSelected': false},
      {'index': 3, 'isSelected': false},
      {'index': 4, 'isSelected': false},
      {'index': 5, 'isSelected': false},
      {'index': 6, 'isSelected': false},
      {'index': 7, 'isSelected': false},
    ];

    showDialog(
        context: context,
        builder: (context) => AlertDialog(
              title: Text("Single select dialog"),
              contentPadding:
                  EdgeInsets.symmetric(vertical: 12, horizontal: 24),
              content: Container(
                height: 240,
                width: 200,
                child: ListView.builder(
                  itemBuilder: (context, index) => StatefulBuilder(
                        builder: (context, StateSetter setState) {
                          return Container(
                            child: CheckboxListTile(
                                title: Text("选择$index"),
                                value: listData[index]['isSelected'],
                                onChanged: (value) {
                                  setState(() {
                                    listData.forEach(
                                        (item) => item['isSelected'] = false);
                                    listData[index]['isSelected'] = value;
                                  });
                                }),
                          );
                        },
                      ),
                  itemCount: listData.length,
                ),
              ),
              actions: <Widget>[
                FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop("取消");
                  },
                  child: Text("取消"),
                ),
                FlatButton(
                  onPressed: () {
                    //采集被选中的项
                    String hasSeletItem = "";
                    listData.forEach((item) {
                      if (item['isSelected']) {
                        hasSeletItem = "$hasSeletItem ${item['index']} ";
                      }
                    });

                    Navigator.of(context).pop(hasSeletItem);
                  },
                  child: Text("确定"),
                )
              ],
            )).then((value) => print(value));
  }

  /// 自定义的 dialog 加载框
  void showCustomLoadingDialog() {
    showDialog(
        barrierDismissible: true,
        context: context,
        builder: (context) => LoadingDialog(text: "loading dialog11111111111"));

//    showDialog(
//        barrierDismissible: true,
//        context: context,
//        builder: (context) => NoticeDialog(
//              title: "关于我们",
//              content:
//                  "比如我想显示一个菊花的loading加载框，那么用上面的方法都是行不通的。这个时候就需要我们去自定义一个对话框,"
//                  "首先我们可以先去看一下Dialog的源码实现，然后只需再照着源码的实现，修改一下就行了。大部分代码是保持一致的，所以对话框的显示效果比如动画，主题都是一致的下面是Dialog源码中的build方法实现。简单的修改下child属性所传的参数就行了",
//            ));

//    showDialog(
//        barrierDismissible: true,
//        context: context,
//        builder: (context) => LoadingDialog1(loadingMsg: "loading dialog"));
  }
}

///这种采用 继承Dialog的方法，存在的问题，会copy过多的代码过来
class LoadingDialog extends Dialog {
  String text;

  LoadingDialog({Key key, @required this.text}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final DialogTheme dialogTheme = DialogTheme.of(context);
    return AnimatedPadding(
      padding: MediaQuery.of(context).viewInsets +
          const EdgeInsets.symmetric(horizontal: 40.0, vertical: 24.0),
      duration: insetAnimationDuration,
      curve: insetAnimationCurve,
      child: MediaQuery.removeViewInsets(
        removeLeft: true,
        removeTop: true,
        removeRight: true,
        removeBottom: true,
        context: context,
        child: Center(
          child: ConstrainedBox(
            constraints: const BoxConstraints(minWidth: 160.0),
            child: SizedBox(
              width: 160,
              height: 160,
              child: Material(
                color: backgroundColor ??
                    dialogTheme.backgroundColor ??
                    Theme.of(context).dialogBackgroundColor,
                type: MaterialType.card,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    CircularProgressIndicator(),
                    Padding(
                      padding: EdgeInsets.all(20),
                      child: Text(
                        text,
                        style: TextStyle(fontSize: 20),
                      ),
                    )
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );

    ///下面这种写法存在问题，dialog不会随着点击空白区域消失，尽管showDialog 的 barrierDismissible参数已经设置为了true,尝试寻找原因
    ///处理方案：可以在外层套 GestureDetector 手势进行处理规避上面的问题
//    return GestureDetector(
//      onTap: () {
//        Navigator.of(context).pop();
//      },
//      child: Material(
//        //创建透明层
//        type: MaterialType.transparency, //透明类型
//        child: Center(
//            child: GestureDetector(
//          onTap: () {},
//          child: SizedBox(
//            width: 120.0,
//            height: 120.0,
//            child: Container(
//              decoration: ShapeDecoration(
//                color: Color(0xffffffff),
//                shape: RoundedRectangleBorder(
//                  borderRadius: BorderRadius.all(
//                    Radius.circular(8.0),
//                  ),
//                ),
//              ),
//              child: Column(
//                mainAxisAlignment: MainAxisAlignment.center,
//                crossAxisAlignment: CrossAxisAlignment.center,
//                children: <Widget>[
//                  CircularProgressIndicator(),
//                  Padding(
//                    padding: const EdgeInsets.only(
//                      top: 20.0,
//                    ),
//                    child: Text(
//                      text,
//                      style: new TextStyle(fontSize: 12.0),
//                    ),
//                  ),
//                ],
//              ),
//            ),
//          ),
//        )),
//      ),
//    );
  }
}

/// 自定义dialog
class NoticeDialog extends Dialog {
  String title;
  String content;

  NoticeDialog({Key key, @required this.title, @required this.content})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Material(
      type: MaterialType.transparency,
      child: Center(
        child: Container(
          margin: EdgeInsets.all(40),
          width: 320,
          height: 400,
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(8))),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              _buildTitle(),
              Container(
                height: 0.7,
                color: Colors.grey,
              ),
              _buildContentText(),
              _buildBottomCenterButton(context)
            ],
          ),
        ),
      ),
    );
  }

  _buildTitle() {
    return Padding(
      padding: EdgeInsets.all(10),
      child: Stack(
        alignment: Alignment.center,
        children: <Widget>[
          Center(
            child: Text(
              title,
              style: TextStyle(fontSize: 18),
            ),
          ),
          Align(
            alignment: Alignment.centerRight,
            child: Icon(
              Icons.close,
              size: 20,
            ),
          )
        ],
      ),
    );
  }

  _buildContentText() {
    return Expanded(
      flex: 1,
      child: Padding(
          padding: EdgeInsets.all(10),
          child: SingleChildScrollView(
            scrollDirection: Axis.vertical,
            child: Text(
              content * 5,
              style: TextStyle(fontSize: 16, color: Colors.grey),
            ),
          )),
    );
  }

  _buildBottomCenterButton(BuildContext context) {
    return Align(
      alignment: Alignment.bottomCenter,
      child: FlatButton(
          onPressed: () {
            Navigator.of(context).pop();
          },
          child: Text(
            "确定",
            style: TextStyle(fontSize: 18),
          )),
    );
  }
}
